package net.ealden.dao.hibernate;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;

import net.ealden.dao.PaginatedDao;
import net.ealden.dao.QueryBuilder;
import net.ealden.model.PagingDetail;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class PaginatedDaoHibernate<T, PK extends Serializable> extends HibernateDaoSupport implements
		PaginatedDao<T, PK> {
	
	@SuppressWarnings("unchecked")
	public List<PK> getKeyList(final QueryBuilder queryBuilder) {
		return (List) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Query query = queryBuilder.getKeyListQuery(session);
			
				return query.list();
			}			
		});
	}

	@SuppressWarnings("unchecked")
	public List<T> getList(final QueryBuilder queryBuilder, final PagingDetail detail) {
		return (List) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Query query = queryBuilder.getListQuery(session);
				
				if (detail != null) {
					query.setFirstResult(detail.getFirstResult());
					query.setMaxResults(detail.getMaxResults());
				}
				
				return query.list();
			}			
		});
	}
}
